<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/icon.png">
  <link rel="mask-icon" href="/blog/images/icon.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bgape002.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="软件设计模式的概念与意义1. 软件设计模式的概念软件设计模式（Software Design Pattern），又称设计模式，是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。它描述了在软件设计过程中的一些不断重复发生的问题，以及该问题的解决方案。也就是说，它是解决特定问题的一系列套路，是前辈们的代码设计经验的总结，具有一定的普遍性，可以反复使用。其目的是为了提高代码的可重用性、">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式">
<meta property="og:url" content="https://bgape002.gitee.io/2022/01/24/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/index.html">
<meta property="og:site_name" content="bgape002">
<meta property="og:description" content="软件设计模式的概念与意义1. 软件设计模式的概念软件设计模式（Software Design Pattern），又称设计模式，是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。它描述了在软件设计过程中的一些不断重复发生的问题，以及该问题的解决方案。也就是说，它是解决特定问题的一系列套路，是前辈们的代码设计经验的总结，具有一定的普遍性，可以反复使用。其目的是为了提高代码的可重用性、">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-01-24T01:46:47.000Z">
<meta property="article:modified_time" content="2022-01-27T02:03:29.248Z">
<meta property="article:author" content="bgape002">
<meta property="article:tag" content="设计模式">
<meta property="article:tag" content="python">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://bgape002.gitee.io/2022/01/24/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>设计模式 | bgape002</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">bgape002</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">淡泊明志，宁静致远</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">66</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">27</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">61</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bgape002.gitee.io/2022/01/24/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/head.png">
      <meta itemprop="name" content="bgape002">
      <meta itemprop="description" content="mail: bgape002@163.com">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="bgape002">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          设计模式
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-01-24 09:46:47" itemprop="dateCreated datePublished" datetime="2022-01-24T09:46:47+08:00">2022-01-24</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-01-27 10:03:29" itemprop="dateModified" datetime="2022-01-27T10:03:29+08:00">2022-01-27</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/software-engineering/" itemprop="url" rel="index"><span itemprop="name">software engineering</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2022/01/24/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2022/01/24/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="软件设计模式的概念与意义"><a href="#软件设计模式的概念与意义" class="headerlink" title="软件设计模式的概念与意义"></a>软件设计模式的概念与意义</h2><h4 id="1-软件设计模式的概念"><a href="#1-软件设计模式的概念" class="headerlink" title="1. 软件设计模式的概念"></a>1. 软件设计模式的概念</h4><p>软件设计模式（Software Design Pattern），又称设计模式，是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。它描述了在软件设计过程中的一些不断重复发生的问题，以及该问题的解决方案。也就是说，它是解决特定问题的一系列套路，是前辈们的代码设计经验的总结，具有一定的普遍性，可以反复使用。其<strong>目的是</strong>为了提高代码的可重用性、代码的可读性和代码的可靠性。</p>
<h4 id="2-学习设计模式的意义"><a href="#2-学习设计模式的意义" class="headerlink" title="2. 学习设计模式的意义"></a>2. 学习设计模式的意义</h4><p>设计模式的<strong>本质是</strong>面向对象设计原则的实际运用，是对类的封装性、继承性和多态性以及类的关联关系和组合关系的充分理解。正确使用设计模式具有以下优点</p>
<ul>
<li>可以提高程序员的思维能力、编程能力和设计能力。</li>
<li>使程序设计更加标准化、代码编制更加工程化，使软件开发效率大大提高，从而缩短软件的开发周期。</li>
<li>使设计的代码可重用性高、可读性强、可靠性高、灵活性好、可维护性强。</li>
</ul>
<span id="more"></span>

<h2 id="UML统一建模语言"><a href="#UML统一建模语言" class="headerlink" title="UML统一建模语言"></a>UML统一建模语言</h2><ul>
<li><a target="_blank" rel="noopener" href="http://c.biancheng.net/view/8373.html">UML统一建模语言是什么？</a></li>
<li><a target="_blank" rel="noopener" href="http://c.biancheng.net/view/8374.html">UML类图及类图之间的关系</a></li>
<li><a target="_blank" rel="noopener" href="http://c.biancheng.net/view/8375.html">类关系记忆技巧</a></li>
</ul>
<h2 id="软件设计七大原则"><a href="#软件设计七大原则" class="headerlink" title="软件设计七大原则"></a>软件设计七大原则</h2><p> 分别为开闭原则、里氏替换原则、依赖倒置原则、单一职责原则、接口隔离原则、迪米特法则和合成复用原则。 这些原则的目的只有一个：<strong>降低对象之间的耦合，增加程序的可复用性、可扩展性和可维护性</strong>。</p>
<table>
<thead>
<tr>
<th>设计原则</th>
<th>一句话归纳</th>
<th>目的</th>
</tr>
</thead>
<tbody><tr>
<td>开闭原则</td>
<td>对扩展开放，对修改关闭</td>
<td>降低维护带来的新风险</td>
</tr>
<tr>
<td>依赖倒置原则</td>
<td>高层不应该依赖低层，要面向接口编程</td>
<td>更利于代码结构的升级扩展</td>
</tr>
<tr>
<td>单一职责原则</td>
<td>一个类只干一件事，实现类要单一</td>
<td>便于理解，提高代码的可读性</td>
</tr>
<tr>
<td>接口隔离原则</td>
<td>一个接口只干一件事，接口要精简单一</td>
<td>功能解耦，高聚合、低耦合</td>
</tr>
<tr>
<td>迪米特法则</td>
<td>不该知道的不要知道，一个类应该保持对其它对象最少的了解，降低耦合度</td>
<td>只和朋友交流，不和陌生人说话，减少代码臃肿</td>
</tr>
<tr>
<td>里氏替换原则</td>
<td>不要破坏继承体系，子类重写方法功能发生改变，不应该影响父类方法的含义</td>
<td>防止继承泛滥</td>
</tr>
<tr>
<td>合成复用原则</td>
<td>尽量使用组合或者聚合关系实现代码复用，少使用继承</td>
<td>降低代码耦合</td>
</tr>
</tbody></table>
<h2 id="GoF-的-23-种设计模式的分类和功能"><a href="#GoF-的-23-种设计模式的分类和功能" class="headerlink" title="GoF 的 23 种设计模式的分类和功能"></a>GoF 的 23 种设计模式的分类和功能</h2><p> GoF<code>(“四人帮”,指Gamma, Helm, Johnson &amp; Vlissides, Addison-Wesley )</code></p>
<ol>
<li><p><strong>根据目的来分：</strong>根据模式是用来完成什么工作来划分，这种方式可分为创建型模式结构型模行为型模式</p>
<ol>
<li>创建型模式：用于描述“怎样创建对象”，它的主要特点是“将对象的创建与使用分离”。GoF 中提供了单例、原型、工厂方法、抽象工厂、建造者等 5 种创建型模式。</li>
<li>结构型模式：用于描述如何将类或对象按某种布局组成更大的结构，GoF 中提供了代理、适配器、桥接、装饰、外观、享元、组合等 7 种结构型模式。</li>
<li>行为型模式：用于描述类或对象之间怎样相互协作共同完成单个对象都无法单独完成的任务，以及怎样分配职责。GoF 中提供了模板方法、策略、命令、职责链、状态、观察者、中介者、迭代器、访问者、备忘录、解释器等 11 种行为型模式。</li>
</ol>
</li>
<li><p><strong>根据作用范围来分：</strong>根据模式是主要用于类上还是主要用于对象上来分，这种方式可分为类模式对象模式</p>
</li>
<li><p>类模式：用于处理类与子类之间的关系，这些关系通过继承来建立，是静态的，在编译时刻便确定下来了。工厂方法、（类）适配器、模板方法、解释器。</p>
<ol start="2">
<li>对象模式：用于处理对象之间的关系，这些关系可以通过组合或聚合来实现，在运行时刻是可以变化的，更具动态性。GoF 中除了以上 4 种，其他的都是对象模式。</li>
</ol>
</li>
</ol>
<h2 id="创建型模式"><a href="#创建型模式" class="headerlink" title="创建型模式"></a>创建型模式</h2><p>创建型模式的主要关注点是“怎样创建对象？”，它的<strong>主要特点是“将对象的创建与使用分离”</strong>。这样可以降低系统的耦合度，使用者不需要关注对象的创建细节，对象的创建由相关的工厂来完成。 </p>
<h3 id="单例（Singleton）模式："><a href="#单例（Singleton）模式：" class="headerlink" title="单例（Singleton）模式："></a>单例（Singleton）模式：</h3><p>某个类只能生成一个实例，该类提供了一个全局访问点供外部获取该实例，其拓展是有限多例模式。</p>
<h4 id="单例模式的优点："><a href="#单例模式的优点：" class="headerlink" title="单例模式的优点："></a>单例模式的优点：</h4><ul>
<li>单例模式可以保证内存里只有一个实例，减少了内存的开销。</li>
<li>可以避免对资源的多重占用。</li>
<li>单例模式设置全局访问点，可以优化和共享资源的访问。</li>
</ul>
<h4 id="单例模式的缺点："><a href="#单例模式的缺点：" class="headerlink" title="单例模式的缺点："></a>单例模式的缺点：</h4><ul>
<li>单例模式一般没有接口，扩展困难。如果要扩展，则除了修改原来的代码，没有第二种途径，违背开闭原则。</li>
<li>在并发测试中，单例模式不利于代码调试。在调试过程中，如果单例中的代码没有执行完，也不能模拟生成一个新的对象。</li>
<li>单例模式的功能代码通常写在一个类中，如果功能设计不合理，则很容易违背单一职责原则。</li>
</ul>
<h4 id="单例模式的应用场景"><a href="#单例模式的应用场景" class="headerlink" title="单例模式的应用场景"></a>单例模式的应用场景</h4><ul>
<li>需要频繁创建的一些类，使用单例可以降低系统的内存压力，减少 GC。</li>
<li>某类只要求生成一个对象的时候，如一个班中的班长、每个人的身份证号等。</li>
<li>某些类创建实例时占用资源较多，或实例化耗时较长，且经常使用。</li>
<li>某类需要频繁实例化，而创建的对象又频繁被销毁的时候，如多线程的线程池、网络连接池等。</li>
<li>频繁访问数据库或文件的对象。</li>
<li>对于一些控制硬件级别的操作，或者从系统上来讲应当是单一控制逻辑的操作，如果有多个实例，则系统会完全乱套。</li>
<li>当对象需要被共享的场合。由于单例模式只允许创建一个对象，共享该对象可以节省内存，并加快对象访问速度。如 Web 中的配置对象、数据库的连接池等。</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Singleton</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__new__</span>(<span class="params">cls, *args, **kwargs</span>):</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> <span class="built_in">hasattr</span>(cls, <span class="string">&quot;_instance&quot;</span>):</span><br><span class="line">            cls._instance = <span class="built_in">super</span>(Singleton, cls).__new__(cls)</span><br><span class="line">        <span class="keyword">return</span> cls._instance</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyClass</span>(<span class="title class_ inherited__">Singleton</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, a</span>):</span><br><span class="line">        self.a = a</span><br><span class="line"></span><br><span class="line">ms1 = MyClass(<span class="number">1</span>)</span><br><span class="line">ms2 = MyClass(<span class="number">2</span>)</span><br><span class="line"><span class="built_in">print</span>(ms1.a, ms2.a)</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(ms1), <span class="built_in">id</span>(ms2))</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">2 2</span></span><br><span class="line"><span class="string">139843914173312 139843914173312</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>



<h3 id="原型（Prototype）模式："><a href="#原型（Prototype）模式：" class="headerlink" title="原型（Prototype）模式："></a>原型（Prototype）模式：</h3><p>将一个对象作为原型，通过对其进行复制而克隆出多个和原型类似的新实例。</p>
<h4 id="原型模式的优点："><a href="#原型模式的优点：" class="headerlink" title="原型模式的优点："></a>原型模式的优点：</h4><ul>
<li>原型模式基于内存二进制流的复制，在性能上比直接 new 一个对象更加优良。</li>
<li>可以使用深克隆方式保存对象的状态，使用原型模式将对象复制一份，并将其状态保存起来，简化了创建对象的过程，以便在需要的时候使用（例如恢复到历史某一状态），可辅助实现撤销操作。</li>
</ul>
<h4 id="原型模式的缺点："><a href="#原型模式的缺点：" class="headerlink" title="原型模式的缺点："></a>原型模式的缺点：</h4><ul>
<li>需要为每一个类都配置一个 clone 方法</li>
<li>clone 方法位于类的内部，当对已有类进行改造的时候，需要修改代码，违背了开闭原则。</li>
<li>当实现深克隆时，需要编写较为复杂的代码，而且当对象之间存在多重嵌套引用时，为了实现深克隆，每一层对象对应的类都必须支持深克隆，实现起来会比较麻烦。因此，深克隆、浅克隆需要运用得当。</li>
</ul>
<h3 id="简单工厂方法（Simple-Factory-Method）模式："><a href="#简单工厂方法（Simple-Factory-Method）模式：" class="headerlink" title="简单工厂方法（Simple Factory Method）模式："></a>简单工厂方法（Simple Factory Method）模式：</h3><p> 定义一个创建产品对象的工厂接口，将产品对象的实际创建工作推迟到具体子工厂类当中。 </p>
<h4 id="优点："><a href="#优点：" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>工厂类包含必要的逻辑判断，可以决定在什么时候创建哪一个产品的实例。客户端可以免除直接创建产品对象的职责，很方便的创建出相应的产品。工厂和产品的职责区分明确。</li>
<li>客户端无需知道所创建具体产品的类名，只需知道参数即可。</li>
<li>也可以引入配置文件，在不修改客户端代码的情况下更换和添加新的具体产品类。</li>
</ul>
<h4 id="缺点："><a href="#缺点：" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li>简单工厂模式的工厂类单一，负责所有产品的创建，职责过重，一旦异常，整个系统将受影响。且工厂类代码会非常臃肿，违背高聚合原则。</li>
<li>使用简单工厂模式会增加系统中类的个数（引入新的工厂类），增加系统的复杂度和理解难度</li>
<li>系统扩展困难，一旦增加新产品不得不修改工厂逻辑，在产品类型较多时，可能造成逻辑过于复杂</li>
<li>简单工厂模式使用了 static 工厂方法，造成工厂角色无法形成基于继承的等级结构。</li>
</ul>
<h4 id="模式的结构"><a href="#模式的结构" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>工厂方法模式的主要角色如下</p>
<ol>
<li>简单工厂（SimpleFactory）：是简单工厂模式的核心，负责实现创建所有实例的内部逻辑。工厂类的创建产品类的方法可以被外界直接调用，创建所需的产品对象。</li>
<li>抽象产品（Product）：是简单工厂创建的所有对象的父类，负责描述所有实例共有的公共接口。</li>
<li>具体产品（ConcreteProduct）：是简单工厂模式的创建目标。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 抽象产品角色，以什么样的表现去使用</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Payment</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pay</span>(<span class="params">self, money</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 产品角色</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Alipay</span>(<span class="title class_ inherited__">Payment</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, use_huabei=<span class="literal">False</span></span>):</span><br><span class="line">        self.use_huabei = use_huabei</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pay</span>(<span class="params">self, money</span>):</span><br><span class="line">        <span class="keyword">if</span> self.use_huabei == <span class="literal">True</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&quot;花呗支付了&#123;0&#125;元!&quot;</span>.<span class="built_in">format</span>(money))</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&quot;支付宝余额支付了&#123;0&#125;元!&quot;</span>.<span class="built_in">format</span>(money))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 产品角色</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">WechatPay</span>(<span class="title class_ inherited__">Payment</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pay</span>(<span class="params">self, money</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;微信支付了%d元!&quot;</span> % (money))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 工厂类角色</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">PaymentFactory</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">ctreate_payment</span>(<span class="params">self, method</span>):</span><br><span class="line">        <span class="keyword">if</span> method == <span class="string">&#x27;Alipay&#x27;</span>:</span><br><span class="line">            <span class="keyword">return</span> Alipay()</span><br><span class="line">        <span class="keyword">elif</span> method == <span class="string">&#x27;WechatPay&#x27;</span>:</span><br><span class="line">            <span class="keyword">return</span> WechatPay()</span><br><span class="line">        <span class="keyword">elif</span> method == <span class="string">&#x27;HuabeiPay&#x27;</span>:</span><br><span class="line">            <span class="keyword">return</span> Alipay(use_huabei=<span class="literal">True</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">raise</span> TypeError(<span class="string">&#x27;No such payment named %s&#x27;</span> % method)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 客户端调用。不直接向客户端暴露对象创建的实现细节，而是通过一个工厂类来负责创建产品类的实例</span></span><br><span class="line">pf = PaymentFactory()</span><br><span class="line">p = pf.ctreate_payment(<span class="string">&#x27;HuabeiPay&#x27;</span>)</span><br><span class="line">p.pay(<span class="number">100</span>)</span><br></pre></td></tr></table></figure>



<h3 id="工厂方法（Factory-Method）模式："><a href="#工厂方法（Factory-Method）模式：" class="headerlink" title="工厂方法（Factory Method）模式："></a>工厂方法（Factory Method）模式：</h3><p>定义一个用于创建产品的接口，由子类决定生产什么产品。</p>
<h4 id="优点：-1"><a href="#优点：-1" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>用户只需要知道具体工厂的名称就可得到所要的产品，无须知道产品的具体创建过程。</li>
<li>灵活性增强，对于新产品的创建，只需多写一个相应的工厂类。</li>
<li>典型的解耦框架。高层模块只需要知道产品的抽象类，无须关心其他实现类，满足迪米特法则、依赖倒置原则和里氏替换原则。</li>
</ul>
<h4 id="缺点：-1"><a href="#缺点：-1" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li>类的个数容易过多，增加复杂度</li>
<li>增加了系统的抽象性和理解难度</li>
<li>抽象产品只能生产一种产品，此弊端可使用抽象工厂模式解决。</li>
</ul>
<h4 id="模式的结构-1"><a href="#模式的结构-1" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>工厂方法模式的主要角色如下</p>
<ol>
<li>抽象工厂（Abstract Factory）：提供了创建产品的接口，调用者通过它访问具体工厂的工厂方法 newProduct() 来创建产品。</li>
<li>具体工厂（ConcreteFactory）：主要是实现抽象工厂中的抽象方法，完成具体产品的创建。</li>
<li>抽象产品（Product）：定义了产品的规范，描述了产品的主要特性和功能。</li>
<li>具体产品（ConcreteProduct）：实现了抽象产品角色所定义的接口，由具体工厂来创建，它同具体工厂之间一一对应。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"></span><br><span class="line"><span class="comment"># 抽象产品角色</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Payment</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pay</span>(<span class="params">self, money</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 具体产品角色</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Alipay</span>(<span class="title class_ inherited__">Payment</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, use_huabei=<span class="literal">False</span></span>):</span><br><span class="line">        self.use_huabei = use_huabei</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pay</span>(<span class="params">self, money</span>):</span><br><span class="line">        <span class="keyword">if</span> self.use_huabei == <span class="literal">True</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&quot;花呗支付了&#123;0&#125;元!&quot;</span>.<span class="built_in">format</span>(money))</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&quot;支付宝余额支付了&#123;0&#125;元!&quot;</span>.<span class="built_in">format</span>(money))</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">WechatPay</span>(<span class="title class_ inherited__">Payment</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pay</span>(<span class="params">self, money</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;微信支付了%d元!&quot;</span> % (money))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 抽象工厂角色</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">PaymentFactory</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">create_payment</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 具体工厂角色</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">AlipayFactory</span>(<span class="title class_ inherited__">PaymentFactory</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">create_payment</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> Alipay()</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">WechatPayFactory</span>(<span class="title class_ inherited__">PaymentFactory</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">create_payment</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> Alipay()</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">HuabeiFactory</span>(<span class="title class_ inherited__">PaymentFactory</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">create_payment</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> Alipay(use_huabei=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">hfp = HuabeiFactory().create_payment()</span><br><span class="line">hfp.pay(<span class="number">100</span>)  <span class="comment"># 花呗支付了100元!</span></span><br></pre></td></tr></table></figure>



<h3 id="抽象工厂（AbstractFactory）模式："><a href="#抽象工厂（AbstractFactory）模式：" class="headerlink" title="抽象工厂（AbstractFactory）模式："></a>抽象工厂（AbstractFactory）模式：</h3><p>提供一个创建产品族的接口，其每个子类可以生产一系列相关的产品。</p>
<h4 id="优点：-2"><a href="#优点：-2" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>可以在类的内部对产品族中相关联的多等级产品共同管理，而不必专门引入多个新的类来进行管理。</li>
<li>当需要产品族时，抽象工厂可以保证客户端始终只使用同一个产品的产品组。</li>
<li>抽象工厂增强了程序的可扩展性，当增加一个新的产品族时，不需要修改原代码，满足开闭原则</li>
</ul>
<h4 id="缺点：-2"><a href="#缺点：-2" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li> 当产品族中需要增加一个新的产品时，所有的工厂类都需要进行修改。增加了系统的抽象性和理解难度。 </li>
</ul>
<h4 id="模式的结构-2"><a href="#模式的结构-2" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>抽象工厂模式的主要角色如下。</p>
<ol>
<li>抽象工厂（Abstract Factory）：提供了创建产品的接口，它包含多个创建产品的方法 newProduct()，可以创建多个不同等级的产品。</li>
<li>具体工厂（Concrete Factory）：主要是实现抽象工厂中的多个抽象方法，完成具体产品的创建。</li>
<li>抽象产品（Product）：定义了产品的规范，描述了产品的主要特性和功能，抽象工厂模式有多个抽象产品。</li>
<li>具体产品（ConcreteProduct）：实现了抽象产品角色所定义的接口，由具体工厂来创建，它同具体工厂之间是多对一的关系。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"></span><br><span class="line"><span class="comment"># ------抽象的产品------</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">PhoneShell</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_shell</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">PhoneCPU</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_cpu</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">PhoneOS</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_os</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">        </span><br><span class="line"><span class="comment"># ------具体的产品------</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">SmallShell</span>(<span class="title class_ inherited__">PhoneShell</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_shell</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;普通手机小手机壳&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BigShell</span>(<span class="title class_ inherited__">PhoneShell</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_shell</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;普通手机大手机壳&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">AppleShell</span>(<span class="title class_ inherited__">PhoneShell</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_shell</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;苹果手机壳&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">SnapDragonCPU</span>(<span class="title class_ inherited__">PhoneCPU</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_cpu</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;骁龙CPU&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">HuaweiCPU</span>(<span class="title class_ inherited__">PhoneCPU</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_cpu</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;化为CPU&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">AppleCPU</span>(<span class="title class_ inherited__">PhoneCPU</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_cpu</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;苹果CPU&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">AndroidOS</span>(<span class="title class_ inherited__">PhoneOS</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_os</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;IOS系统&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">AppleOS</span>(<span class="title class_ inherited__">PhoneOS</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_os</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;安卓系统&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># ------抽象的工厂------</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">PhoneFactory</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">make_shell</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">make_cpu</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">make_os</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># ------具体的工厂------</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">HuaweiFactory</span>(<span class="title class_ inherited__">PhoneFactory</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">make_shell</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> SmallShell()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">make_cpu</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> HuaweiCPU()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">make_os</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> AndroidOS()</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">AppleFactory</span>(<span class="title class_ inherited__">PhoneFactory</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">make_shell</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> AppleShell()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">make_cpu</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> AppleCPU()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">make_os</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> AppleOS()</span><br><span class="line"></span><br><span class="line"><span class="comment"># ------客户端------</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Phone</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, shell, cpu, os</span>):</span><br><span class="line">        self.shell = shell</span><br><span class="line">        self.cpu = cpu</span><br><span class="line">        self.os = os</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">show_info</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;手机信息：&#x27;</span>)</span><br><span class="line">        self.shell.show_shell()</span><br><span class="line">        self.cpu.show_cpu()</span><br><span class="line">        self.os.show_os()</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">make_phone</span>(<span class="params">factory</span>):</span><br><span class="line">    shell = factory.make_shell()</span><br><span class="line">    cpu = factory.make_cpu()</span><br><span class="line">    os = factory.make_os()</span><br><span class="line">    <span class="keyword">return</span> Phone(shell, cpu, os)</span><br><span class="line"></span><br><span class="line">p = make_phone(HuaweiFactory())</span><br><span class="line">p.show_info()</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">手机信息：</span></span><br><span class="line"><span class="string">普通手机小手机壳</span></span><br><span class="line"><span class="string">化为CPU</span></span><br><span class="line"><span class="string">IOS系统</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>



<h3 id="建造者（Builder）模式："><a href="#建造者（Builder）模式：" class="headerlink" title="建造者（Builder）模式："></a>建造者（Builder）模式：</h3><p>将一个复杂对象分解成多个相对简单的部分，然后根据不同需要分别创建它们，最后构建成该复杂对象。</p>
<h4 id="优点：-3"><a href="#优点：-3" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>封装性好，构建和表示分离。</li>
<li>扩展性好，各个具体的建造者相互独立，有利于系统的解耦。</li>
<li>客户端不必知道产品内部组成的细节，建造者可以对创建过程逐步细化，而不对其它模块产生任何影响，便于控制细节风险。</li>
</ul>
<h4 id="缺点：-3"><a href="#缺点：-3" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li>产品的组成部分必须相同，这限制了其使用范围。</li>
<li>如果产品的内部变化复杂，如果产品内部发生变化，则建造者也要同步修改，后期维护成本较大。 </li>
</ul>
<h4 id="模式的结构-3"><a href="#模式的结构-3" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>建造者（Builder）模式的主要角色如下。</p>
<ol>
<li>产品角色（Product）：它是包含多个组成部件的复杂对象，由具体建造者来创建其各个零部件。</li>
<li>抽象建造者（Builder）：它是一个包含创建产品各个子部件的抽象方法的接口，通常还包含一个返回复杂产品的方法 getResult()。</li>
<li>具体建造者(Concrete Builder）：实现 Builder 接口，完成复杂产品的各个部件的具体创建方法。</li>
<li>指挥者（Director）：它调用建造者对象中的部件构造与装配方法完成复杂对象的创建，在指挥者中不涉及具体产品的信息。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"></span><br><span class="line"><span class="comment"># ------产品------</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Player</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, face=<span class="literal">None</span>, body=<span class="literal">None</span>, arms=<span class="literal">None</span>, legs=<span class="literal">None</span></span>):</span><br><span class="line">        self.face = face</span><br><span class="line">        self.body = body</span><br><span class="line">        self.arms = arms</span><br><span class="line">        self.legs = legs</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__str__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;%s,%s,%s,%s&#x27;</span> % (self.face, self.body, self.arms, self.legs)</span><br><span class="line"></span><br><span class="line"><span class="comment"># ------抽象建造者------</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">PlayerBuilder</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_face</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_body</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_arms</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_legs</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># ------具体建造者,隐藏了一个产品的内部结构------</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">GirlBuilder</span>(<span class="title class_ inherited__">PlayerBuilder</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self.player = Player()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_face</span>(<span class="params">self</span>):</span><br><span class="line">        self.player.face = <span class="string">&#x27;漂亮的脸蛋&#x27;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_body</span>(<span class="params">self</span>):</span><br><span class="line">        self.player.body = <span class="string">&#x27;苗条的身材&#x27;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_arms</span>(<span class="params">self</span>):</span><br><span class="line">        self.player.arms = <span class="string">&#x27;细细的胳膊&#x27;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_legs</span>(<span class="params">self</span>):</span><br><span class="line">        self.player.legs = <span class="string">&#x27;大长腿&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># ------具体建造者，表示代码------</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MonsterBuilder</span>(<span class="title class_ inherited__">PlayerBuilder</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self.player = Player()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_face</span>(<span class="params">self</span>):</span><br><span class="line">        self.player.face = <span class="string">&#x27;绿脸&#x27;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_body</span>(<span class="params">self</span>):</span><br><span class="line">        self.player.body = <span class="string">&#x27;魁梧的身体&#x27;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_arms</span>(<span class="params">self</span>):</span><br><span class="line">        self.player.arms = <span class="string">&#x27;粗壮的胳膊&#x27;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build_legs</span>(<span class="params">self</span>):</span><br><span class="line">        self.player.legs = <span class="string">&#x27;粗壮的大腿&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># ------指挥者，构造代码(构造代码和表示代码分开)，可以对构造过程进行更加精细地控制------</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">PlayerDirectory</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">builder_player</span>(<span class="params">self, builder</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        隐藏了装配过程</span></span><br><span class="line"><span class="string">        :param builder:</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        builder.build_face()</span><br><span class="line">        builder.build_body()</span><br><span class="line">        builder.build_arms()</span><br><span class="line">        builder.build_legs()</span><br><span class="line">        <span class="keyword">return</span> builder.player</span><br><span class="line"></span><br><span class="line"><span class="comment"># ------客户端------</span></span><br><span class="line">builder = GirlBuilder()</span><br><span class="line">director = PlayerDirectory()</span><br><span class="line">p = director.builder_player(builder)</span><br><span class="line"><span class="built_in">print</span>(p)  <span class="comment"># 漂亮的脸蛋,苗条的身材,细细的胳膊,大长腿</span></span><br></pre></td></tr></table></figure>

<h2 id="结构型模式"><a href="#结构型模式" class="headerlink" title="结构型模式"></a>结构型模式</h2><p>结构型模式描述如何将类或对象按某种布局组成更大的结构。</p>
<p>它<strong>分为类结构型模式和对象结构型模式</strong>，前者采用继承机制来组织接口和类，后者釆用组合或聚合来组合对象。 </p>
<h3 id="代理（Proxy）模式："><a href="#代理（Proxy）模式：" class="headerlink" title="代理（Proxy）模式："></a>代理（Proxy）模式：</h3><p>为某对象提供一种代理以控制对该对象的访问。即客户端通过代理间接地访问该对象，从而限制、增强或修改该对象的一些特性。</p>
<h4 id="优点：-4"><a href="#优点：-4" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>代理模式在客户端与目标对象之间起到一个中介作用和保护目标对象的作用；</li>
<li>代理对象可以扩展目标对象的功能；</li>
<li>代理模式能将客户端与目标对象分离，在一定程度上降低了系统的耦合度，增加了程序的可扩展性</li>
</ul>
<h4 id="缺点：-4"><a href="#缺点：-4" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li>代理模式会造成系统设计中类的数量增加</li>
<li>在客户端和目标对象之间增加一个代理对象，会造成请求处理速度变慢；</li>
<li>增加了系统的复杂度；</li>
</ul>
<h4 id="模式的结构-4"><a href="#模式的结构-4" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>代理模式的主要角色如下。</p>
<ol>
<li>抽象主题（Subject）类：通过接口或抽象类声明真实主题和代理对象实现的业务方法。</li>
<li>真实主题（Real Subject）类：实现了抽象主题中的具体业务，是代理对象所代表的真实对象，是最终要引用的对象。</li>
<li>代理（Proxy）类：提供了与真实主题相同的接口，其内部含有对真实主题的引用，它可以访问、控制或扩展真实主题的功能。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Subject</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_content</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">set_content</span>(<span class="params">self, content</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">RealSubject</span>(<span class="title class_ inherited__">Subject</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, filename</span>):</span><br><span class="line">        self.filename = filename</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;读取文件内容！&#x27;</span>)</span><br><span class="line">        <span class="keyword">with</span> <span class="built_in">open</span>(self.filename, <span class="string">&#x27;r&#x27;</span>, encoding=<span class="string">&#x27;utf-8&#x27;</span>) <span class="keyword">as</span> f:</span><br><span class="line">            self.content = f.read()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_content</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> self.content</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">set_content</span>(<span class="params">self, content</span>):</span><br><span class="line">        <span class="keyword">with</span> <span class="built_in">open</span>(self.filename, <span class="string">&#x27;w&#x27;</span>, encoding=<span class="string">&#x27;utf-8&#x27;</span>) <span class="keyword">as</span> f:</span><br><span class="line">            f.write(content)</span><br><span class="line"></span><br><span class="line">subj = RealSubject(<span class="string">&#x27;test.txt&#x27;</span>)</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">读取文件内容！</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<p>​    不使用虚代理，只要是实例化 RealSubject 类，就会读取这个文件占用内存。使用虚代理后，可以和根据需要创建对象，用户不调用是不会创建 RealSubject 对象的，节省了内存的开销。如果需要只有读的权限而没有写的权限，可以使用保护代理： </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Subject</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_content</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">set_content</span>(<span class="params">self, content</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">RealSubject</span>(<span class="title class_ inherited__">Subject</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, filename</span>):</span><br><span class="line">        self.filename = filename</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;读取文件内容！&#x27;</span>)</span><br><span class="line">        <span class="keyword">with</span> <span class="built_in">open</span>(self.filename, <span class="string">&#x27;r&#x27;</span>, encoding=<span class="string">&#x27;utf-8&#x27;</span>) <span class="keyword">as</span> f:</span><br><span class="line">            self.content = f.read()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_content</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> self.content</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">set_content</span>(<span class="params">self, content</span>):</span><br><span class="line">        <span class="keyword">with</span> <span class="built_in">open</span>(self.filename, <span class="string">&#x27;w&#x27;</span>, encoding=<span class="string">&#x27;utf-8&#x27;</span>) <span class="keyword">as</span> f:</span><br><span class="line">            f.write(content)</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ProtectedSubject</span>(<span class="title class_ inherited__">Subject</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, filename</span>):</span><br><span class="line">        self.subj = RealSubject(filename)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_content</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> self.subj.get_content()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">set_content</span>(<span class="params">self, content</span>):</span><br><span class="line">        <span class="keyword">raise</span> PermissionError(<span class="string">&#x27;无写入权限！&#x27;</span>)</span><br><span class="line"></span><br><span class="line">subj = ProtectedSubject(<span class="string">&#x27;test.txt&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(subj.get_content())</span><br><span class="line">subj.set_content(<span class="string">&#x27;abc&#x27;</span>)</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">读取文件内容！</span></span><br><span class="line"><span class="string">test file!</span></span><br><span class="line"><span class="string">Traceback (most recent call last):</span></span><br><span class="line"><span class="string">  File &quot;/home/thanlon/projects/PycharmProjects/untitled/代理模式.py&quot;, line 42, in &lt;module&gt;</span></span><br><span class="line"><span class="string">    subj.set_content(&#x27;abc&#x27;)</span></span><br><span class="line"><span class="string">  File &quot;/home/thanlon/projects/PycharmProjects/untitled/代理模式.py&quot;, line 37, in set_content</span></span><br><span class="line"><span class="string">    raise PermissionError(&#x27;无写入权限！&#x27;)</span></span><br><span class="line"><span class="string">PermissionError: 无写入权限！</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>



<h3 id="适配器（Adapter）模式："><a href="#适配器（Adapter）模式：" class="headerlink" title="适配器（Adapter）模式："></a>适配器（Adapter）模式：</h3><p>将一个类的接口转换成客户希望的另外一个接口，使得原本由于接口不兼容而不能一起工作的那些类能一起工作。</p>
<h4 id="优点：-5"><a href="#优点：-5" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>客户端通过适配器可以透明地调用目标接口。</li>
<li>复用了现存的类，程序员不需要修改原有代码而重用现有的适配者类。</li>
<li>将目标类和适配者类解耦，解决了目标类和适配者类接口不一致的问题。</li>
<li>在很多业务场景中符合开闭原则。</li>
</ul>
<h4 id="缺点：-5"><a href="#缺点：-5" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li>适配器编写过程需要结合业务场景全面考虑，可能会增加系统的复杂性。</li>
<li>增加代码阅读难度，降低代码可读性，过多使用适配器会使系统代码变得凌乱。</li>
</ul>
<h4 id="模式的结构-5"><a href="#模式的结构-5" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>适配器模式（Adapter）包含以下主要角色。</p>
<ol>
<li>目标（Target）接口：当前系统业务所期待的接口，它可以是抽象类或接口。</li>
<li>适配者（Adaptee）类：它是被访问和适配的现存组件库中的组件接口。</li>
<li>适配器（Adapter）类：它是一个转换器，通过继承或引用适配者的对象，把适配者接口转换成目标接口，让客户按目标接口的格式访问适配者。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 类适配器模式使用示例：</span></span><br><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"></span><br><span class="line"><span class="comment"># 目标接口</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Payment</span>(<span class="built_in">object</span>, metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pay</span>(<span class="params">self, money</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Alipay</span>(<span class="title class_ inherited__">Payment</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pay</span>(<span class="params">self, money</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;支付了%d&#x27;</span> % money)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 待适配的类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BankPay</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">cost</span>(<span class="params">self, money</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;银联支付了%d&#x27;</span> % money)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 类适配器</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">PaymentAdapter</span>(Payment, BankPay):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    把不兼容cost转换成pay</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pay</span>(<span class="params">self, money</span>):</span><br><span class="line">        self.cost(money)</span><br><span class="line"></span><br><span class="line">p = PaymentAdapter()</span><br><span class="line">p.pay(<span class="number">100</span>)</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">银联支付了100</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>



<h3 id="桥接（Bridge）模式："><a href="#桥接（Bridge）模式：" class="headerlink" title="桥接（Bridge）模式："></a>桥接（Bridge）模式：</h3><p>将抽象与实现分离，使它们可以独立变化。它是用组合关系代替继承关系来实现，从而降低了抽象和实现这两个可变维度的耦合度。</p>
<h4 id="优点：-6"><a href="#优点：-6" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>抽象与实现分离，扩展能力强</li>
<li>符合开闭原则</li>
<li>符合合成复用原则</li>
<li>其实现细节对客户透明</li>
</ul>
<h4 id="缺点：-6"><a href="#缺点：-6" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li> 由于聚合关系建立在抽象层，要求开发者针对抽象化进行设计与编程，能正确地识别出系统中两个独立变化的维度，这增加了系统的理解与设计难度。  </li>
</ul>
<h4 id="模式的结构-6"><a href="#模式的结构-6" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>桥接（Bridge）模式包含以下主要角色。</p>
<ol>
<li>抽象化（Abstraction）角色：定义抽象类，并包含一个对实现化对象的引用。</li>
<li>扩展抽象化（Refined Abstraction）角色：是抽象化角色的子类，实现父类中的业务方法，并通过组合关系调用实现化角色中的业务方法。</li>
<li>实现化（Implementor）角色：定义实现化角色的接口，供扩展抽象化角色调用。</li>
<li>具体实现化（Concrete Implementor）角色：给出实现化角色接口的具体实现。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"></span><br><span class="line"><span class="comment"># 抽象</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Shape</span>(metaclass=ABCMeta):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, color</span>):</span><br><span class="line">        self.color = color</span><br><span class="line"></span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">draw</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 实现</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Color</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">paint</span>(<span class="params">self, shape</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 细化抽象</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Rectangle</span>(<span class="title class_ inherited__">Shape</span>):</span><br><span class="line">    name = <span class="string">&#x27;长方形&#x27;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">draw</span>(<span class="params">self</span>):</span><br><span class="line">        self.color.paint(self)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果要扩展形状，只需要添加形状类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Circle</span>(<span class="title class_ inherited__">Shape</span>):</span><br><span class="line">    name = <span class="string">&#x27;圆形&#x27;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">draw</span>(<span class="params">self</span>):</span><br><span class="line">        self.color.paint(self)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 细化实现</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Red</span>(<span class="title class_ inherited__">Color</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">paint</span>(<span class="params">self, shape</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;画红色的%s&#x27;</span> % shape.name)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果要扩展颜色，只需要添加颜色类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Green</span>(<span class="title class_ inherited__">Color</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">paint</span>(<span class="params">self, shape</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;画绿色的%s&#x27;</span> % shape.name)</span><br><span class="line"></span><br><span class="line">rectangle = Rectangle(Red())</span><br><span class="line">rectangle.draw()</span><br><span class="line">circle = Circle(Green())</span><br><span class="line">circle.draw()</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">画红色的长方形</span></span><br><span class="line"><span class="string">画绿色的圆形</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>



<h3 id="装饰（Decorator）模式："><a href="#装饰（Decorator）模式：" class="headerlink" title="装饰（Decorator）模式："></a>装饰（Decorator）模式：</h3><p>动态的给对象增加一些职责，即增加其额外的功能。</p>
<h3 id="外观（Facade）模式："><a href="#外观（Facade）模式：" class="headerlink" title="外观（Facade）模式："></a>外观（Facade）模式：</h3><p>为多个复杂的子系统提供一个一致的接口，使这些子系统更加容易被访问。</p>
<h4 id="优点：-7"><a href="#优点：-7" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>降低了子系统与客户端之间的耦合度，使得子系统的变化不会影响调用它的客户类。</li>
<li>对客户屏蔽了子系统组件，减少了客户处理的对象数目，并使得子系统使用起来更加容易。</li>
<li>降低了大型软件系统中的编译依赖性，简化了系统在不同平台之间的移植过程，因为编译一个子系统不会影响其他的子系统，也不会影响外观对象。</li>
</ul>
<h4 id="缺点：-7"><a href="#缺点：-7" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li>不能很好地限制客户使用子系统类，很容易带来未知风险。</li>
<li>增加新的子系统可能需要修改外观类或客户端的源代码，违背了“开闭原则”。 </li>
</ul>
<h4 id="模式的结构-7"><a href="#模式的结构-7" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>外观（Facade）模式包含以下主要角色。</p>
<ol>
<li>外观（Facade）角色：为多个子系统对外提供一个共同的接口。</li>
<li>子系统（Sub System）角色：实现系统的部分功能，客户可以通过外观角色访问它。</li>
<li>客户（Client）角色：通过一个外观角色访问各个子系统的功能。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 子系统类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">CPU</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">run</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;CPU start to run...&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">stop</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;CPU stop to run...&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 子系统类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Disk</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">run</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;Disk start to run...&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">stop</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;Disk stop to run...&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 子系统类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Memory</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">run</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;Memory start to run...&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">stop</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;Memory stop to run...&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 外观</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Computer</span>():</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self.CPU = CPU()</span><br><span class="line">        self.Disc = Disk()</span><br><span class="line">        self.Member = Memory()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">run</span>(<span class="params">self</span>):</span><br><span class="line">        self.CPU.run()</span><br><span class="line">        self.Disc.run()</span><br><span class="line">        self.Member.run()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">stop</span>(<span class="params">self</span>):</span><br><span class="line">        self.CPU.stop()</span><br><span class="line">        self.Disc.stop()</span><br><span class="line">        self.Member.stop()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 客户端，高层代码</span></span><br><span class="line">c = Computer()</span><br><span class="line">c.run()</span><br><span class="line">c.stop()</span><br></pre></td></tr></table></figure>



<h3 id="享元（Flyweight）模式："><a href="#享元（Flyweight）模式：" class="headerlink" title="享元（Flyweight）模式："></a>享元（Flyweight）模式：</h3><p>运用共享技术来有效地支持大量细粒度对象的复用。</p>
<h3 id="组合（Composite）模式："><a href="#组合（Composite）模式：" class="headerlink" title="组合（Composite）模式："></a>组合（Composite）模式：</h3><p>将对象组合成树状层次结构，使用户对单个对象和组合对象具有一致的访问性。</p>
<h4 id="优点：-8"><a href="#优点：-8" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>组合模式使得客户端代码可以一致地处理单个对象和组合对象，无须关心自己处理的是单个对象，还是组合对象，这简化了客户端代码；</li>
<li>更容易在组合体内加入新的对象，客户端不会因为加入了新的对象而更改源代码，满足“开闭原则”；</li>
</ul>
<h4 id="缺点：-8"><a href="#缺点：-8" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li>设计较复杂，客户端需要花更多时间理清类之间的层次关系；</li>
<li>不容易限制容器中的构件；</li>
<li>不容易用继承的方法来增加构件的新功能；</li>
</ul>
<h4 id="模式的结构-8"><a href="#模式的结构-8" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>组合模式包含以下主要角色。</p>
<ol>
<li>抽象构件（Component）角色：它的主要作用是为树叶构件和树枝构件声明公共接口，并实现它们的默认行为。在透明式的组合模式中抽象构件还声明访问和管理子类的接口；在安全式的组合模式中不声明访问和管理子类的接口，管理工作由树枝构件完成。（总的抽象类或接口，定义一些通用的方法，比如新增、删除）</li>
<li>树叶构件（Leaf）角色：是组合中的叶节点对象，它没有子节点，用于继承或实现抽象构件。</li>
<li>树枝构件（Composite）角色 / 中间构件：是组合中的分支节点对象，它有子节点，用于继承和实现抽象构件。它的主要作用是存储和管理子部件，通常包含 Add()、Remove()、GetChild() 等方法。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"></span><br><span class="line"><span class="comment"># 抽象组件</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Graphic</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">draw</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 叶子组件</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Point</span>(<span class="title class_ inherited__">Graphic</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, x, y</span>):</span><br><span class="line">        self.x = x</span><br><span class="line">        self.y = y</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__str__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;点(%s,%s)&#x27;</span> % (self.x, self.y)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">draw</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(self)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 叶子组件</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Line</span>(<span class="title class_ inherited__">Graphic</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, p1, p2</span>):</span><br><span class="line">        self.p1 = p1</span><br><span class="line">        self.p2 = p2</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__str__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;线段[(%s,%s)]&#x27;</span> % (self.p1, self.p2)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">draw</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(self)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 复合组件</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Picture</span>(<span class="title class_ inherited__">Graphic</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, iterable</span>):</span><br><span class="line">        self.children = []</span><br><span class="line">        <span class="keyword">for</span> g <span class="keyword">in</span> iterable:</span><br><span class="line">            self.add(g)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">add</span>(<span class="params">self, graphic</span>):</span><br><span class="line">        self.children.append(graphic)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">draw</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">for</span> g <span class="keyword">in</span> self.children:</span><br><span class="line">            g.draw()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 简单图形</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;------简单图形------&#x27;</span>)</span><br><span class="line">p = Point(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line">l1 = Line(Point(<span class="number">1</span>, <span class="number">2</span>), Point(<span class="number">3</span>, <span class="number">4</span>))</span><br><span class="line">l2 = Line(Point(<span class="number">5</span>, <span class="number">6</span>), Point(<span class="number">7</span>, <span class="number">8</span>))</span><br><span class="line"><span class="built_in">print</span>(p)</span><br><span class="line"><span class="built_in">print</span>(l1)</span><br><span class="line"><span class="built_in">print</span>(l2)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;------复合图形(p,l1,l2)------&#x27;</span>)</span><br><span class="line"><span class="comment"># 复合图形</span></span><br><span class="line">pic = Picture([p, l1, l2])</span><br><span class="line">pic.draw()</span><br></pre></td></tr></table></figure>

<h2 id="行为型模式"><a href="#行为型模式" class="headerlink" title="行为型模式"></a>行为型模式</h2><p>行为型模式<strong>分为类行为模式和对象行为模式</strong>，前者采用继承机制来在类间分派行为，后者采用组合或聚合在对象间分配行为。</p>
<p>由于组合关系或聚合关系比继承关系耦合度低，满足“合成复用原则”，所以对象行为模式比类行为模式具有更大的灵活性。 </p>
<h3 id="模板方法（TemplateMethod）模式："><a href="#模板方法（TemplateMethod）模式：" class="headerlink" title="模板方法（TemplateMethod）模式："></a>模板方法（TemplateMethod）模式：</h3><p>定义一个操作中的算法骨架，而将算法的一些步骤延迟到子类中，使得子类可以不改变该算法结构的情况下重定义该算法的某些特定步骤。</p>
<h4 id="优点：-9"><a href="#优点：-9" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>它封装了不变部分，扩展可变部分。它把认为是不变部分的算法封装到父类中实现，而把可变部分算法由子类继承实现，便于子类继续扩展。</li>
<li>它在父类中提取了公共的部分代码，便于代码复用。</li>
<li><strong>部分方法是由子类实现的</strong>，因此子类可以通过扩展方式增加相应的功能，符合开闭原则。</li>
</ul>
<h4 id="缺点：-9"><a href="#缺点：-9" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li>对每个不同的实现都需要定义一个子类，这会导致类的个数增加，系统更加庞大，设计也更加抽象，间接地增加了系统实现的复杂度。</li>
<li>父类中的抽象方法由子类实现，子类执行的结果会影响父类的结果，这导致一种反向的控制结构，它提高了代码阅读的难度。</li>
<li>由于继承关系自身的缺点，如果父类添加新的抽象方法，则所有子类都要改一遍。</li>
</ul>
<h4 id="模式的结构-9"><a href="#模式的结构-9" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>模板方法：定义了算法的骨架，按某种顺序调用其包含的基本方法。<br>② 基本方法：是整个算法中的一个步骤，包含以下几种类型</p>
<ul>
<li>抽象方法：在抽象类中声明，由具体子类实现。</li>
<li>具体方法：在抽象类中已经实现，在具体子类中可以继承或重写它。</li>
<li>钩子方法：在抽象类中已经实现，包括用于判断的逻辑方法和需要子类重写的空方法两种。</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"><span class="keyword">from</span> time <span class="keyword">import</span> sleep</span><br><span class="line"></span><br><span class="line"><span class="comment"># 抽象类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Window</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">start</span>(<span class="params">self</span>):  <span class="comment"># 原子操作/钩子操作</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">repaint</span>(<span class="params">self</span>):  <span class="comment"># 原子操作/钩子操作</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">stop</span>(<span class="params">self</span>):  <span class="comment"># 原子操作/钩子操作</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">run</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        模板方法(具体方法)，这个大逻辑就不需要自己写了</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.start()</span><br><span class="line">        <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">            <span class="keyword">try</span>:</span><br><span class="line">                self.repaint()</span><br><span class="line">                sleep(<span class="number">1</span>)</span><br><span class="line">            <span class="keyword">except</span> KeyboardInterrupt:</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">        self.stop()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 具体类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyWindow</span>(<span class="title class_ inherited__">Window</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, msg</span>):</span><br><span class="line">        self.msg = msg</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">start</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;窗口开始运行！&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">stop</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;窗口停止运行！&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">repaint</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(self.msg)</span><br><span class="line"></span><br><span class="line">MyWindow(<span class="string">&quot;Hello...&quot;</span>).run()</span><br></pre></td></tr></table></figure>



<h3 id="策略（Strategy）模式："><a href="#策略（Strategy）模式：" class="headerlink" title="策略（Strategy）模式："></a>策略（Strategy）模式：</h3><p>定义了一系列算法，并将每个算法封装起来，使它们可以相互替换，且算法的改变不会影响使用算法的客户。</p>
<h4 id="优点：-10"><a href="#优点：-10" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>多重条件语句不易维护，而使用策略模式可以避免使用多重条件语句，如 if…else 语句、switch…case 语句。</li>
<li>策略模式提供了一系列的可供重用的算法族，恰当使用继承可以把算法族的公共代码转移到父类里面，从而避免重复的代码。</li>
<li>策略模式可以提供相同行为的不同实现，客户可以根据不同时间或空间要求选择不同的。</li>
<li>策略模式提供了对开闭原则的完美支持，可以在不修改原代码的情况下，灵活增加新算法。</li>
<li>策略模式把算法的使用放到环境类中，而算法的实现移到具体策略类中，实现了二者的分离。</li>
</ul>
<h4 id="缺点：-10"><a href="#缺点：-10" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li>客户端必须理解所有策略算法的区别，以便适时选择恰当的算法类。</li>
<li>策略模式造成很多的策略类，增加维护难度。</li>
</ul>
<h4 id="模式的结构-10"><a href="#模式的结构-10" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>策略模式的主要角色如下</p>
<ol>
<li>抽象策略（Strategy）类：定义了一个公共接口，各种不同的算法以不同的方式实现这个接口，环境角色使用这个接口调用不同的算法，一般使用接口或抽象类实现。</li>
<li>具体策略（Concrete Strategy）类：实现了抽象策略定义的接口，提供具体的算法实现。</li>
<li>环境（Context）类：持有一个策略类的引用，最终给客户端调用。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> abstractmethod, ABCMeta</span><br><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> datetime</span><br><span class="line"></span><br><span class="line"><span class="comment"># 抽象策略</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Strategy</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">execute</span>(<span class="params">self, data</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 具体策略</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">FastStrategy</span>(<span class="title class_ inherited__">Strategy</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">execute</span>(<span class="params">self, data</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;使用较快的策略处理%s&quot;</span> % data)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 具体策略</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">SlowStrategy</span>(<span class="title class_ inherited__">Strategy</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">execute</span>(<span class="params">self, data</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;使用较慢的策略处理%s&quot;</span> % data)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 上下文</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Context</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, strategy, data</span>):</span><br><span class="line">        self.data = data</span><br><span class="line">        self.strategy = strategy</span><br><span class="line">        <span class="comment"># 可以定义用户不知道的东西</span></span><br><span class="line">        self.date = datetime.now()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">set_strategy</span>(<span class="params">self, strategy</span>):</span><br><span class="line">        self.strategy = strategy</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">do_strategy</span>(<span class="params">self</span>):</span><br><span class="line">        self.strategy.execute(self.data)</span><br><span class="line"></span><br><span class="line">data = <span class="string">&quot;Hello!&quot;</span></span><br><span class="line"><span class="comment"># 使用较快的策略处理</span></span><br><span class="line">fast_strategy = FastStrategy()</span><br><span class="line">context = Context(fast_strategy, data)</span><br><span class="line">context.do_strategy()</span><br><span class="line"><span class="comment"># 使用较慢的策略处理</span></span><br><span class="line">slow_strategy = SlowStrategy()</span><br><span class="line">context = Context(slow_strategy, data)</span><br><span class="line">context.do_strategy()</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">使用较快的策略处理Hello!</span></span><br><span class="line"><span class="string">使用较慢的策略处理Hello!</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>



<h3 id="命令（Command）模式："><a href="#命令（Command）模式：" class="headerlink" title="命令（Command）模式："></a>命令（Command）模式：</h3><p>将一个请求封装为一个对象，使发出请求的责任和执行请求的责任分割开。</p>
<h3 id="职责链（Chain-of-Responsibility）模式："><a href="#职责链（Chain-of-Responsibility）模式：" class="headerlink" title="职责链（Chain of Responsibility）模式："></a>职责链（Chain of Responsibility）模式：</h3><p>把请求从链中的一个对象传到下一个对象，直到请求被响应为止。通过这种方式去除对象之间的耦合。</p>
<h4 id="优点：-11"><a href="#优点：-11" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>降低了对象之间的耦合度。该模式使得一个对象无须知道到底是哪一个对象处理其请求以及链的结构，发送者和接收者也无须拥有对方的明确信息。</li>
<li>增强了系统的可扩展性。可以根据需要增加新的请求处理类，满足开闭原则。</li>
<li>增强了给对象指派职责的灵活性。当工作流程发生变化，可以动态地改变链内的成员或者调动它们的次序，也可动态地新增或者删除责任。</li>
<li>责任链简化了对象之间的连接。每个对象只需保持一个指向其后继者的引用，不需保持其他所有处理者的引用，这避免了使用众多的 if 或者 if···else 语句。</li>
<li>责任分担。每个类只需要处理自己该处理的工作，不该处理的传递给下一个对象完成，明确各类的责任范围，符合类的单一职责原则。</li>
</ul>
<h4 id="缺点：-11"><a href="#缺点：-11" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li>不能保证每个请求一定被处理。由于一个请求没有明确的接收者，所以不能保证它一定会被处理，该请求可能一直传到链的末端都得不到处理。</li>
<li>对比较长的职责链，请求的处理可能涉及多个处理对象，系统性能将受到一定影响。</li>
<li>职责链建立的合理性要靠客户端来保证，增加了客户端的复杂性，可能会由于职责链的错误设置而导致系统出错，如可能会造成循环调用。</li>
</ul>
<h4 id="模式的结构-11"><a href="#模式的结构-11" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>职责链模式主要包含以下角色。</p>
<ol>
<li>抽象处理者（Handler）角色：定义一个处理请求的接口，包含抽象处理方法和一个后继连接。</li>
<li>具体处理者（Concrete Handler）角色：实现抽象处理者的处理方法，判断能否处理本次请求，如果可以处理请求则处理，否则将该请求转给它的后继者。</li>
<li>客户类（Client）角色：创建处理链，并向链头的具体处理者对象提交请求，它不关心处理细节和请求的传递过程。</li>
</ol>
<p>责任链模式的本质是解耦请求与处理，让请求在处理链中能进行传递与被处理；理解责任链模式应当理解其模式，而不是其具体实现。责任链模式的独到之处是将其节点处理者组合成了链式结构，并允许节点自身决定是否进行请求处理或转发，相当于让请求流动起来。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"></span><br><span class="line"><span class="comment"># 抽象的处理者</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Handler</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">handle_leave</span>(<span class="params">self, day</span>):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 具体的处理者</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">GeneralManager</span>(<span class="title class_ inherited__">Handler</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">handle_leave</span>(<span class="params">self, day</span>):</span><br><span class="line">        <span class="keyword">if</span> day &lt;= <span class="number">30</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&#x27;总经理准假%d&#x27;</span> % day)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&#x27;可以辞职了！&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 具体的处理者</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">DepartmentManager</span>(<span class="title class_ inherited__">Handler</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self.<span class="built_in">next</span> = GeneralManager()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">handle_leave</span>(<span class="params">self, day</span>):</span><br><span class="line">        <span class="keyword">if</span> day &lt;= <span class="number">7</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&#x27;项目主管准假%d&#x27;</span> % day)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&#x27;部门经理职权不足&#x27;</span>)</span><br><span class="line">            self.<span class="built_in">next</span>.handle_leave(day)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 具体的处理者</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ProjectDirector</span>(<span class="title class_ inherited__">Handler</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self.<span class="built_in">next</span> = DepartmentManager()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">handle_leave</span>(<span class="params">self, day</span>):</span><br><span class="line">        <span class="keyword">if</span> day &lt;= <span class="number">3</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&#x27;项目主管准假%d&#x27;</span> % day)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&#x27;项目主管职权不足&#x27;</span>)</span><br><span class="line">            self.<span class="built_in">next</span>.handle_leave(day)</span><br><span class="line"></span><br><span class="line">day = <span class="number">20</span></span><br><span class="line">p = ProjectDirector()</span><br><span class="line">p.handle_leave(day)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">项目主管职权不足</span></span><br><span class="line"><span class="string">部门经理职权不足</span></span><br><span class="line"><span class="string">总经理准假20</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>



<h3 id="状态（State）模式："><a href="#状态（State）模式：" class="headerlink" title="状态（State）模式："></a>状态（State）模式：</h3><p>允许一个对象在其内部状态发生改变时改变其行为能力。</p>
<h3 id="观察者（Observer）模式："><a href="#观察者（Observer）模式：" class="headerlink" title="观察者（Observer）模式："></a>观察者（Observer）模式：</h3><p>多个对象间存在一对多关系，当一个对象发生改变时，把这种改变通知给其他多个对象，从而影响其他对象的行为。</p>
<h4 id="优点：-12"><a href="#优点：-12" class="headerlink" title="优点："></a>优点：</h4><ul>
<li>降低了目标与观察者之间的耦合关系，两者之间是抽象耦合关系。符合依赖倒置原则。</li>
<li>目标与观察者之间建立了一套触发机制。</li>
</ul>
<h4 id="缺点：-12"><a href="#缺点：-12" class="headerlink" title="缺点："></a>缺点：</h4><ul>
<li>目标与观察者之间的依赖关系并没有完全解除，而且有可能出现循环引用。</li>
<li>当观察者对象很多时，通知的发布会花费很多时间，影响程序的效率。 </li>
</ul>
<h4 id="模式的结构-12"><a href="#模式的结构-12" class="headerlink" title="模式的结构"></a>模式的结构</h4><p>观察者模式的主要角色如下。</p>
<ol>
<li>抽象主题（Subject）角色：也叫抽象目标类，它提供了一个用于保存观察者对象的聚集类和增加、删除观察者对象的方法，以及通知所有观察者的抽象方法。</li>
<li>具体主题（Concrete Subject）角色：也叫具体目标类，它实现抽象目标中的通知方法，当具体主题的内部状态发生改变时，通知所有注册过的观察者对象。</li>
<li>抽象观察者（Observer）角色：它是一个抽象类或接口，它包含了一个更新自己的抽象方法，当接到具体主题的更改通知时被调用。</li>
<li>具体观察者（Concrete Observer）角色：实现抽象观察者中定义的抽象方法，以便在得到目标的更改通知时更新自身的状态。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> abc <span class="keyword">import</span> ABCMeta, abstractmethod</span><br><span class="line"></span><br><span class="line"><span class="comment"># 抽象的订阅者</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Observer</span>(metaclass=ABCMeta):</span><br><span class="line"><span class="meta">    @abstractmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">update</span>(<span class="params">self, notice</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :param notice: Notice类的对象</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 抽象的发布者：可以是接口，子类不需要实现，所以不需要定义抽象方法！</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Notice</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self.observers = []</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">attach</span>(<span class="params">self, obs</span>):</span><br><span class="line">        self.observers.append(obs)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">detach</span>(<span class="params">self, obs</span>):</span><br><span class="line">        self.observers.remove(obs)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">notify</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        推送</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">for</span> obs <span class="keyword">in</span> self.observers:</span><br><span class="line">            obs.update(self)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 具体的发布者</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">StaffNotice</span>(<span class="title class_ inherited__">Notice</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, company_info</span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__()  <span class="comment"># 调用父类对象声明observers属性</span></span><br><span class="line">        self.__company_info = company_info</span><br><span class="line"></span><br><span class="line"><span class="meta">    @property</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">company_info</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> self.__company_info</span><br><span class="line"></span><br><span class="line"><span class="meta">    @company_info.setter</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">company_info</span>(<span class="params">self, info</span>):</span><br><span class="line">        self.__company_info = info</span><br><span class="line">        self.notify()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 具体的订阅者</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Staff</span>(<span class="title class_ inherited__">Observer</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self.company_info = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">update</span>(<span class="params">self, notice</span>):</span><br><span class="line">        self.company_info = notice.company_info</span><br><span class="line"></span><br><span class="line">staff_notice = StaffNotice(<span class="string">&#x27;初始化公司信息&#x27;</span>)</span><br><span class="line">staff1 = Staff()</span><br><span class="line">staff2 = Staff()</span><br><span class="line">staff_notice.attach(staff1)</span><br><span class="line">staff_notice.attach(staff2)</span><br><span class="line"><span class="comment"># print(staff1.company_info) None</span></span><br><span class="line"><span class="comment"># print(staff2.company_info) None</span></span><br><span class="line">staff_notice.company_info = <span class="string">&#x27;假期放假通知！&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(staff1.company_info)</span><br><span class="line"><span class="built_in">print</span>(staff2.company_info)</span><br><span class="line">staff_notice.detach(staff2)</span><br><span class="line">staff_notice.company_info = <span class="string">&#x27;明天开会！&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(staff1.company_info)</span><br><span class="line"><span class="built_in">print</span>(staff2.company_info)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">假期放假通知！</span></span><br><span class="line"><span class="string">假期放假通知！</span></span><br><span class="line"><span class="string">明天开会！</span></span><br><span class="line"><span class="string">假期放假通知！</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>



<h3 id="中介者（Mediator）模式："><a href="#中介者（Mediator）模式：" class="headerlink" title="中介者（Mediator）模式："></a>中介者（Mediator）模式：</h3><p>定义一个中介对象来简化原有对象之间的交互关系，降低系统中对象间的耦合度，使原有对象之间不必相互了解。</p>
<h3 id="迭代器（Iterator）模式："><a href="#迭代器（Iterator）模式：" class="headerlink" title="迭代器（Iterator）模式："></a>迭代器（Iterator）模式：</h3><p>提供一种方法来顺序访问聚合对象中的一系列数据，而不暴露聚合对象的内部表示。</p>
<h3 id="访问者（Visitor）模式："><a href="#访问者（Visitor）模式：" class="headerlink" title="访问者（Visitor）模式："></a>访问者（Visitor）模式：</h3><p>在不改变集合元素的前提下，为一个集合中的每个元素提供多种访问方式，即每个元素有多个访问者对象访问。</p>
<h3 id="备忘录（Memento）模式："><a href="#备忘录（Memento）模式：" class="headerlink" title="备忘录（Memento）模式："></a>备忘录（Memento）模式：</h3><p>在不破坏封装性的前提下，获取并保存一个对象的内部状态，以便以后恢复它。</p>
<h3 id="解释器（Interpreter）模式："><a href="#解释器（Interpreter）模式：" class="headerlink" title="解释器（Interpreter）模式："></a>解释器（Interpreter）模式：</h3><p>提供如何定义语言的文法，以及对语言句子的解释方法，即解释器。</p>
<h3 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h3><font size=2>

<p>[1] <a target="_blank" rel="noopener" href="http://c.biancheng.net/view/1317.html">设计模式</a></p>
<p>[2] <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV19541167cn?p=3">Python之常用设计模式</a></p>
<p>[] <a href=""></a></p>
<p></font>&gt;</p>

    </div>

    
    
    

      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/blog/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag"><i class="fa fa-tag"></i> 设计模式</a>
              <a href="/blog/tags/python/" rel="tag"><i class="fa fa-tag"></i> python</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2022/01/20/ssh%E5%9F%BA%E7%A1%80%E4%BD%BF%E7%94%A8/" rel="prev" title="ssh基础使用">
      <i class="fa fa-chevron-left"></i> ssh基础使用
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2022/07/05/python-process-thread/" rel="next" title="python process&thread">
      python process&thread <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>


        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BD%AF%E4%BB%B6%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E7%9A%84%E6%A6%82%E5%BF%B5%E4%B8%8E%E6%84%8F%E4%B9%89"><span class="nav-number">1.</span> <span class="nav-text">软件设计模式的概念与意义</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-%E8%BD%AF%E4%BB%B6%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E7%9A%84%E6%A6%82%E5%BF%B5"><span class="nav-number">1.0.1.</span> <span class="nav-text">1. 软件设计模式的概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-%E5%AD%A6%E4%B9%A0%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E7%9A%84%E6%84%8F%E4%B9%89"><span class="nav-number">1.0.2.</span> <span class="nav-text">2. 学习设计模式的意义</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#UML%E7%BB%9F%E4%B8%80%E5%BB%BA%E6%A8%A1%E8%AF%AD%E8%A8%80"><span class="nav-number">2.</span> <span class="nav-text">UML统一建模语言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BD%AF%E4%BB%B6%E8%AE%BE%E8%AE%A1%E4%B8%83%E5%A4%A7%E5%8E%9F%E5%88%99"><span class="nav-number">3.</span> <span class="nav-text">软件设计七大原则</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#GoF-%E7%9A%84-23-%E7%A7%8D%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E7%9A%84%E5%88%86%E7%B1%BB%E5%92%8C%E5%8A%9F%E8%83%BD"><span class="nav-number">4.</span> <span class="nav-text">GoF 的 23 种设计模式的分类和功能</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-number">5.</span> <span class="nav-text">创建型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8D%95%E4%BE%8B%EF%BC%88Singleton%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">5.1.</span> <span class="nav-text">单例（Singleton）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E7%9A%84%E4%BC%98%E7%82%B9%EF%BC%9A"><span class="nav-number">5.1.1.</span> <span class="nav-text">单例模式的优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BC%BA%E7%82%B9%EF%BC%9A"><span class="nav-number">5.1.2.</span> <span class="nav-text">单例模式的缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E7%9A%84%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-number">5.1.3.</span> <span class="nav-text">单例模式的应用场景</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%EF%BC%88Prototype%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">5.2.</span> <span class="nav-text">原型（Prototype）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F%E7%9A%84%E4%BC%98%E7%82%B9%EF%BC%9A"><span class="nav-number">5.2.1.</span> <span class="nav-text">原型模式的优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BC%BA%E7%82%B9%EF%BC%9A"><span class="nav-number">5.2.2.</span> <span class="nav-text">原型模式的缺点：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%AE%80%E5%8D%95%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95%EF%BC%88Simple-Factory-Method%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">5.3.</span> <span class="nav-text">简单工厂方法（Simple Factory Method）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A"><span class="nav-number">5.3.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A"><span class="nav-number">5.3.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84"><span class="nav-number">5.3.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95%EF%BC%88Factory-Method%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">5.4.</span> <span class="nav-text">工厂方法（Factory Method）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-1"><span class="nav-number">5.4.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-1"><span class="nav-number">5.4.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-1"><span class="nav-number">5.4.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%8E%82%EF%BC%88AbstractFactory%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">5.5.</span> <span class="nav-text">抽象工厂（AbstractFactory）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-2"><span class="nav-number">5.5.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-2"><span class="nav-number">5.5.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-2"><span class="nav-number">5.5.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BB%BA%E9%80%A0%E8%80%85%EF%BC%88Builder%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">5.6.</span> <span class="nav-text">建造者（Builder）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-3"><span class="nav-number">5.6.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-3"><span class="nav-number">5.6.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-3"><span class="nav-number">5.6.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BB%93%E6%9E%84%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-number">6.</span> <span class="nav-text">结构型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%A3%E7%90%86%EF%BC%88Proxy%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">6.1.</span> <span class="nav-text">代理（Proxy）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-4"><span class="nav-number">6.1.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-4"><span class="nav-number">6.1.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-4"><span class="nav-number">6.1.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%80%82%E9%85%8D%E5%99%A8%EF%BC%88Adapter%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">6.2.</span> <span class="nav-text">适配器（Adapter）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-5"><span class="nav-number">6.2.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-5"><span class="nav-number">6.2.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-5"><span class="nav-number">6.2.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A1%A5%E6%8E%A5%EF%BC%88Bridge%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">6.3.</span> <span class="nav-text">桥接（Bridge）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-6"><span class="nav-number">6.3.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-6"><span class="nav-number">6.3.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-6"><span class="nav-number">6.3.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A3%85%E9%A5%B0%EF%BC%88Decorator%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">6.4.</span> <span class="nav-text">装饰（Decorator）模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A4%96%E8%A7%82%EF%BC%88Facade%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">6.5.</span> <span class="nav-text">外观（Facade）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-7"><span class="nav-number">6.5.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-7"><span class="nav-number">6.5.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-7"><span class="nav-number">6.5.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%AB%E5%85%83%EF%BC%88Flyweight%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">6.6.</span> <span class="nav-text">享元（Flyweight）模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BB%84%E5%90%88%EF%BC%88Composite%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">6.7.</span> <span class="nav-text">组合（Composite）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-8"><span class="nav-number">6.7.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-8"><span class="nav-number">6.7.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-8"><span class="nav-number">6.7.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%A1%8C%E4%B8%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-number">7.</span> <span class="nav-text">行为型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A8%A1%E6%9D%BF%E6%96%B9%E6%B3%95%EF%BC%88TemplateMethod%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">7.1.</span> <span class="nav-text">模板方法（TemplateMethod）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-9"><span class="nav-number">7.1.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-9"><span class="nav-number">7.1.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-9"><span class="nav-number">7.1.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%AD%96%E7%95%A5%EF%BC%88Strategy%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">7.2.</span> <span class="nav-text">策略（Strategy）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-10"><span class="nav-number">7.2.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-10"><span class="nav-number">7.2.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-10"><span class="nav-number">7.2.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%91%BD%E4%BB%A4%EF%BC%88Command%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">7.3.</span> <span class="nav-text">命令（Command）模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%81%8C%E8%B4%A3%E9%93%BE%EF%BC%88Chain-of-Responsibility%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">7.4.</span> <span class="nav-text">职责链（Chain of Responsibility）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-11"><span class="nav-number">7.4.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-11"><span class="nav-number">7.4.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-11"><span class="nav-number">7.4.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%8A%B6%E6%80%81%EF%BC%88State%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">7.5.</span> <span class="nav-text">状态（State）模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A7%82%E5%AF%9F%E8%80%85%EF%BC%88Observer%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">7.6.</span> <span class="nav-text">观察者（Observer）模式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A-12"><span class="nav-number">7.6.1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9A-12"><span class="nav-number">7.6.2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%A8%A1%E5%BC%8F%E7%9A%84%E7%BB%93%E6%9E%84-12"><span class="nav-number">7.6.3.</span> <span class="nav-text">模式的结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%AD%E4%BB%8B%E8%80%85%EF%BC%88Mediator%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">7.7.</span> <span class="nav-text">中介者（Mediator）模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%AD%E4%BB%A3%E5%99%A8%EF%BC%88Iterator%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">7.8.</span> <span class="nav-text">迭代器（Iterator）模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AE%BF%E9%97%AE%E8%80%85%EF%BC%88Visitor%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">7.9.</span> <span class="nav-text">访问者（Visitor）模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A4%87%E5%BF%98%E5%BD%95%EF%BC%88Memento%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">7.10.</span> <span class="nav-text">备忘录（Memento）模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A7%A3%E9%87%8A%E5%99%A8%EF%BC%88Interpreter%EF%BC%89%E6%A8%A1%E5%BC%8F%EF%BC%9A"><span class="nav-number">7.11.</span> <span class="nav-text">解释器（Interpreter）模式：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="nav-number">7.12.</span> <span class="nav-text">参考链接</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="bgape002"
      src="/blog/images/head.png">
  <p class="site-author-name" itemprop="name">bgape002</p>
  <div class="site-description" itemprop="description">mail: bgape002@163.com</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">61</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">66</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2021 – 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">bgape002</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'szhBf0Qamzsowubi1WnkXmUj-gzGzoHsz',
      appKey     : 'WpwxoK0fVJHvhzWwakr9vbpA',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
